//
//  BaseSafariViewController.m
//  Learn
//
//  Created by zyl_macbookpro on 2024/6/6.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "BaseSafariViewController.h"

@interface BaseSafariViewController ()

@end

@implementation BaseSafariViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
- (WKWebView *)webView
{
    if (!_webView) {
        // 可以做一些初始化配置定制
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.selectionGranularity = WKSelectionGranularityDynamic;
        configuration.allowsInlineMediaPlayback = YES;
        
        WKPreferences *preferences = [WKPreferences new];
        //是否支持JavaScript
        preferences.javaScriptEnabled = YES;
        //不通过用户交互，是否可以打开窗口
        preferences.javaScriptCanOpenWindowsAutomatically = NO;
        configuration.mediaTypesRequiringUserActionForPlayback = NO;
        configuration.preferences = preferences;
        [configuration.preferences setValue:@"TRUE" forKey:@"allowFileAccessFromFileURLs"];
    
        // 初始化WKWebView
        _webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds configuration:configuration];
        if (@available(iOS 16.4, *)) {
            [_webView setInspectable:YES];
        } else {
            // Fallback on earlier versions
        }
        _webView.y = lStatusBarHeight;
        _webView.height = lScreenHeight - lStatusBarHeight;
        //[_webView addSubview:self.progressView];
        // 有两种代理，UIDelegate负责界面弹窗，navigationDelegate负责加载、跳转等
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
        [_webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:NULL];
        [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
       

    }
    return _webView;
}
- (UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, lScreenWidth, 1)];
        _progressView.progressTintColor = rgba(12, 183, 108, 1);
        _progressView.trackTintColor = rgba(249, 249, 249, 1);
        _progressView.progressViewStyle=UIProgressViewStyleDefault;
    }
    return _progressView;
}
#pragma mark - WKNavigationDelegate
/* 页面开始加载 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
}
/* 开始返回内容 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
     
}
/* 页面加载完成 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
  
    // 禁止放大缩小
    NSString *injectionJSString = @"var script = document.createElement('meta');"
    "script.name = 'viewport';"
    "script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
    "document.getElementsByTagName('head')[0].appendChild(script);";
    [webView evaluateJavaScript:injectionJSString completionHandler:nil];

}
/* 页面加载失败 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
     
}
/* 在发送请求之前，决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSLog(@"1%@",navigationAction.request.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationActionPolicyCancel);
}
/* 在收到响应后，决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
     
    NSLog(@"2%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    [self wb_userContentController:userContentController didReceiveScriptMessage:message];
}
- (void)wb_userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    
}
#pragma mark - 属性监听
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat estimatedProgress = [change[NSKeyValueChangeNewKey] floatValue];
        NSLog(@"页面加载进度：%f", estimatedProgress);
        [self.progressView setProgress:estimatedProgress];
    }else if ([keyPath isEqualToString:@"loading"]) {
        BOOL loading = [change[NSKeyValueChangeNewKey] boolValue];
        NSLog(@"%@", loading ? @"开始加载" : @"停止加载");
        self.progressView.hidden = !loading;
    }else if ([keyPath isEqualToString:@"title"]) {
        if (self.ingoreTitle) {
            return;
        }
        NSString *title = (NSString *)change[NSKeyValueChangeNewKey];
        self.title = title;
    }
}

- (void)reloadWebviewWithUrl:(NSString *)url
{
    NSString *token = [NSString stringWithFormat:@"?token=%@",lApp.useModel.token];
    if ([url containsString:@"parame="]) {
        url = [url stringByReplacingOccurrencesOfString:@"parame=" withString:token];
        token = @"";
    }
    NSURL *rl=[NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@",webUrl,url,token]];
    NSMutableURLRequest *res =[NSMutableURLRequest requestWithURL:rl];
    [self.webView loadRequest:res];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
